package com.cn.springcloudwechat.shiro;


import com.cn.springcloudwechat.common.utils.base.Const;
import com.cn.springcloudwechat.model.YmUser;
import com.cn.springcloudwechat.model.security.CipherUtil;
import com.cn.springcloudwechat.model.system.account.Account;
import com.cn.springcloudwechat.redis.RedisUtil;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserService;
import com.cn.springcloudwechat.service.system.account.AccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private AccountService accountService;

    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        AuthenticationInfo authenticationInfo = null;
        String username=new String(token.getUsername());//用户名
        String password=new String(token.getPassword());//密码
        Account a = accountService.findFormatByLoginName(username);//通过登录名 寻找用户
        if (a != null) {
            //组合username,两次迭代，对密码进行加密
            String pwdEncrypt = CipherUtil.createPwdEncrypt(username,password,a.getSalt());
            if(a.getPassword().equals(pwdEncrypt)){
                authenticationInfo = new SimpleAuthenticationInfo(a.getLoginName(), password, getName());
                this.setSession(Const.SESSION_USER, a);
                return authenticationInfo;
            }else{
                throw new IncorrectCredentialsException(); 
            }
        } else {
            throw new UnknownAccountException(); 
        }

    }

    
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        // 因为非正常退出，即没有显式调用 SecurityUtils.getSubject().logout()
        // (可能是关闭浏览器，或超时)，但此时缓存依旧存在(principals)，所以会自己跑到授权方法里。
        if (!SecurityUtils.getSubject().isAuthenticated()) {
            doClearCache(pc);
            SecurityUtils.getSubject().logout();
            return null;
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    private void setSession(Object key, Object value) {
        Subject currentUser = SecurityUtils.getSubject();
        if (null != currentUser) {
            Session session = currentUser.getSession();
            if (null != session) {
                session.setAttribute(key, value);
            }
        }
    }


}
